package cn.hg.solon.youcan.system.provider;

import static cn.hg.solon.youcan.system.entity.table.SysDictItemTableDef.SYS_DICT_ITEM;
import static cn.hg.solon.youcan.system.entity.table.SysDictTableDef.SYS_DICT;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Tran;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;

import cn.hg.solon.youcan.common.constant.AppConstants;
import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.system.entity.SysDict;
import cn.hg.solon.youcan.system.mapper.SysDictMapper;
import cn.hg.solon.youcan.system.service.SysDictItemService;
import cn.hg.solon.youcan.system.service.SysDictService;

/**
 * @author 胡高
 */
@Component
public class SysDictProvider extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    @Inject
    SysDictItemService dictItemService;

    @Override
    public boolean checkUnique(SysDict bean) {
        // 查找已存在记录
        QueryWrapper query = QueryWrapper.create()
            .where(SYS_DICT.TYPE.eq(bean.getType())
                .and(SYS_DICT.ID.ne(bean.getId()))
                );

        return ObjUtil.isNull(this.getOne(query));
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.SysDictService#getByTypeAndCode(java.lang.String, java.lang.String)
     */
    @Override
    public SysDict getByType(String type) {
        QueryWrapper query = QueryWrapper.create().where(SYS_DICT.TYPE.eq(type));
        return this.getOne(query);
    }

    @Override
    @Tran
    public Page<SysDict> pageByMap(Page<SysDict> page, Map<String, Object> map) {
        String type = (String)map.get("type");
        String status = (String)map.get("status");
        String word = (String)map.get("word");
        String sortField = (String)map.get("sortField");
        String sortType = (String)map.get("sortType");
        QueryWrapper query = QueryWrapper.create()
            .where(SYS_DICT.TYPE.eq(type).when(StrValidator.isNotBlank(type))
                .and(SYS_DICT.STATUS.eq(status).when(StrValidator.isNotBlank(status)))
                .and(SYS_DICT.NAME.like(word).when(StrValidator.isNotBlank(word))
                    .or(SYS_DICT.TYPE.like(word).when(StrValidator.isNotBlank(word)))
                    )
                );

        if (StrValidator.isNotBlank(sortField) && StrValidator.isNotBlank(sortType)) {
            query.orderBy(new QueryOrderBy(new QueryColumn(CharSequenceUtil.toUnderlineCase(sortField)), sortType));
        }

        return this.page(page, query);
    }

    @Override
    @Tran
    public boolean removeByIds(Collection<? extends Serializable> ids) {
        for (Serializable id : ids) {
            SysDict dict = this.getById(id);

            if (ObjUtil.isNotNull(dict)) {
                if (this.dictItemService.count(SYS_DICT_ITEM.TYPE.eq(dict.getType())) > 0) {
                    throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "[" + dict.getName() + "] 中存在子项，不允许删除！");
                }
            }
        }

        return super.removeByIds(ids);
    }

    @Override
    @Tran
    public boolean save(SysDict bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "字典名称已经存在，请更换其它值！");
        }

        return super.save(bean);
    }

    @Override
    public boolean update(SysDict bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "字典名称已经存在，请更换其它值！");
        }

        /*
         * 更新子项的type名
         */
        this.updateItemType(bean);

        return this.updateById(bean);
    }

    private void updateItemType(SysDict bean) {
        SysDict exist = this.getById(bean.getId());

        /*
         * 如果类型名不变
         */
        if (ObjUtil.isNull(exist) || CharSequenceUtil.equals(bean.getType(), exist.getName())) {
            return;
        }

        /*
         * 如果修改了类型，则需要同步修改子项的类型名
         */
        this.dictItemService.updateTypeName(exist.getType(), bean.getType());
    }
}
